package com.hoku.auth.service;

import com.hoku.auth.dao.IUserDao;
import com.hoku.auth.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.Optional;

/**
 * @author ZHUFEIFEI
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private PasswordEncoder encoder;

    @Autowired
    private IUserDao dao;

    @Override
    public void create(@Valid User user) {
        Optional<User> existing = Optional.ofNullable(this.dao.findByUsername(user.getUsername()));
        existing.ifPresent(it-> {throw new IllegalArgumentException("user already exists: " + it.getUsername());});

        String hash = encoder.encode(user.getPassword());
        user.setPassword(hash);
        user.setAuthorities(AuthorityUtils.createAuthorityList("client_role", "test_role"));
        user.setAccountNonExpired(true);
        user.setAccountNonLocked(true);
        user.setCredentialsNonExpired(true);
        user.setEnabled(true);

        this.dao.save(user);

        log.info("new user has been created: {}", user.getUsername());
    }
}
